package com.huang.controller;

// import com.alibaba.fastjson.JSONObject;
import com.huang.resp.CommonResult;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author han
 * @since 2021-12-30 08:56:45
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @GetMapping("")
    public CommonResult login() {
        return CommonResult.success();
    }

    /**
     * 服务降级
     */
    @HystrixCommand(fallbackMethod = "fallbackA", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    @GetMapping("hystrix/{id}")
    public String hystrix(@PathVariable("id") Long id) {
        if (id < 0) {
            throw new RuntimeException("this is runtimeException");
        }
        return "hystrix";
    }

    public String fallbackA(Long id) {
        return "hystrix==>异常了";
    }


    /**
     * 服务熔断
     */
    @HystrixCommand(fallbackMethod = "fallbackB", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000"),
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"), // 开启熔断
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), // 一段时间内的请求数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "5000"), // 在一段时间内的请求 单位 毫秒 值：5s
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "20"), // 错误百分比，默认50 错误的超过了 就进入降级->熔断->恢复
    })
    @GetMapping("circuit/{id}")
    public String circuit(@PathVariable("id") Long id) {
        if (id < 0) {
            throw new RuntimeException("this is runtimeException");
        }
        return "hystrix" + UUID.randomUUID();
    }

    public String fallbackB(Long id) {
        return "hystrix 熔断服务==>异常了";
    }
}
